package com.example.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.Paper;

import com.example.springboot.mapper.PaperMapper;
import com.example.springboot.service.IPaperService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

@Service
@Slf4j
public class PaperService implements IPaperService {

    @Resource
    PaperMapper paperMapper;


    @Override
    public List<Paper> list() {
        return paperMapper.list();
    }

    @Override
    public PageInfo<Paper> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        return new PageInfo<>(paperMapper.listByCondition(baseRequest));
    }

    @Override
    public void save(Paper obj) {

        obj.setCategory(category(obj.getCategories()));
        paperMapper.save(obj);
    }


    @Override
    public Paper getById(Integer id) {
        return paperMapper.getById(id);
    }

    @Override
    public void update(Paper obj) {

            obj.setCategory(category(obj.getCategories()));
            obj.setUpdatetime(LocalDate.now());
            paperMapper.updateById(obj);



    }

    @Override
    public void deleteById(Integer id) {
        paperMapper.deleteById(id);
    }

    private String category(List<String> categories) {
        StringBuilder sb = new StringBuilder();
        if (CollUtil.isNotEmpty(categories)) {
            categories.forEach(v -> sb.append(v).append(" > "));
            return sb.substring(0, sb.lastIndexOf(" > "));
        }
        return sb.toString();
    }

}